/** 登录、注册 */
import React, { Fragment } from 'react';
import { useRequest} from 'ahooks';
import { Button, Card, Form, Input, Select, Typography, message } from 'antd';
import './index.less';
import { login, register } from '../../services/account';
import { useLogin } from '../../hooks/useIdentity';

interface IProps {
  /** 登录模式 LOGIN，注册模式 REGISTER */
  mode: string;
}

const Login: React.FC<IProps> = ({mode}) => {
  const [form] = Form.useForm();
  const storeLogin = useLogin();
  const onReq = mode === 'LOGIN' ? login : register;
  const {run: doRequest} = useRequest(onReq, {
    manual: true,
    onSuccess: (data: any) => {
      
      if( data.code === 0 && mode === 'LOGIN') {
        const { username, identity} = data.data;
        storeLogin({username, identity});
        message.success(data.msg);
      } else {
        message.error(data.msg);
      }
    }
  });
  const onFinish = () => {
    const values = form.getFieldsValue();
    doRequest(values);
  }
  return (
    <div className='form-container'>
      <Card style={{marginTop: '16px'}}>
      <div style={{fontSize: '32px', width: '100%'}}>
        { mode === 'LOGIN' ? '登录' : '注册'}
      </div>
      <Form 
        form={form}
        labelCol={{ span: 8 }}
        wrapperCol={{ span: 16 }}
        onFinish={onFinish}
        style={{
          marginTop: '24px',
          width: '600px',
        }}>
        {mode === 'LOGIN'
        ? (
          <Fragment>
            <Form.Item 
              label="用户名"
              name="username"
              required
              >
              <Input></Input>
            </Form.Item>
            <Form.Item 
              required
              label="密码"
              name="password"
            >
            <Input></Input>
          </Form.Item>
        </Fragment>
        )
        :(
          <Fragment>
            <Form.Item
              label="身份"
              name="identity"
              required
            >
              <Select options={[
                {
                  key: 'normal',
                  label: '普通用户'
                },
                {
                  key: 'admin',
                  label: '管理员'
                }
              ]}>
              </Select>
            </Form.Item>
            <Form.Item 
              label="用户名"
              name="username"
              required
              >
              <Input></Input>
            </Form.Item>
            <Form.Item 
              label="密码"
              name="password"
              required
            >
            <Input></Input>
          </Form.Item>
        </Fragment>
        )
      } 
        <Form.Item wrapperCol={{ offset: 8, span: 16 }}>
          <Button 
            style={{backgroundColor: '#20ac93', color: 'white'}}
            htmlType='submit'  
          >提交</Button>
        </Form.Item>
      </Form>
    </Card>
    </div>
  )
}

export default Login;